package com.example.choupaiapp.main.fragment;

import android.Manifest;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.bumptech.glide.Glide;
import com.dueeeke.videoplayer.player.VideoViewManager;
import com.example.choupaiapp.R;
import com.example.choupaiapp.common.constant.Contacts;
import com.example.choupaiapp.common.finalokgo.callback.Callback;
import com.example.choupaiapp.common.finalokgo.request.RequestType;
import com.example.choupaiapp.common.ui.fragment.CommonFragment;
import com.example.choupaiapp.common.util.ContextUtil;
import com.example.choupaiapp.common.util.SharedPreferencesHelp;
import com.example.choupaiapp.common.util.Utils;
import com.example.choupaiapp.main.activity.find.FindBannerWebviewActivity;
import com.example.choupaiapp.main.activity.home.CameraActivity;
import com.example.choupaiapp.main.activity.home.LocationActivity;
import com.example.choupaiapp.main.activity.home.SearchActivity;
import com.example.choupaiapp.main.bean.CacheLocationBean;
import com.example.choupaiapp.main.bean.HomeLocationBean;
import com.example.choupaiapp.main.bean.HomeLocationData;
import com.example.choupaiapp.main.bean.HomeTabBean;
import com.example.choupaiapp.main.bean.SendCodeBean;
import com.example.choupaiapp.main.bean.UserInfoBean;
import com.example.choupaiapp.main.bean.VersionBean;
import com.example.choupaiapp.main.constant.Url;
import com.example.choupaiapp.main.fragment.home.RecommendFragment;
import com.example.choupaiapp.main.util.LocationUtil;
import com.example.choupaiapp.main.view.AttachButton;
import com.flyco.tablayout.CommonImageTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.flyco.tablayout.listener.TabEntity;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by ASUS on 2019/10/30.
 */

public class HomeFragment extends CommonFragment implements AMapLocationListener, /*OnTabSelectListener, */ViewPager.OnPageChangeListener, OnRefreshLoadMoreListener {


    @BindView(R.id.home_location)
    TextView homeLocation;
    //    @BindView(R.id.sliding_tablayout)
//    SlidingTabLayout slidingTabLayout;
    @BindView(R.id.common_bottom_tab)
    CommonImageTabLayout commonBottomTab;
    @BindView(R.id.scrollView)
    HorizontalScrollView scrollView;
    @BindView(R.id.viewpager)
    ViewPager viewPager;
    Unbinder unbinder;
    //    @BindView(R.id.refreshLayout)
//    SmartRefreshLayout refreshLayout;
    @BindView(R.id.activit_img)
    AttachButton activit_img;
    @BindView(R.id.home_tip_tv)
    TextView home_tip_tv;
    //    private ArrayList<String> list = new ArrayList<>();
    private ArrayList<RecommendFragment> mFragments = new ArrayList<>();
    private MyPagerAdapter myPagerAdapter;
    private AMapLocation mAMapLocation;
    private String token;
    public static double lat;
    public static double lon;
    private int position = 0;
    private Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (!TextUtils.isEmpty(token)) {
                finalOkGo.requestHead(RequestType.POSTHEAD, Url.WATCH_FIVE_MINUTE, null, Url.WATCH_FIVE_MINUTE, new Callback<SendCodeBean>() {
                    @Override
                    public void onSuccess(SendCodeBean sendCodeBean) {
                        handler.removeCallbacks(runnable);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        handler.removeCallbacks(runnable);
                    }
                });
            }
        }
    };
    private CacheLocationBean cacheLocationBean;
    private HomeTabBean mHomeTabBean;
    public static String province = "";
    public static String city = "";
    private String flag = "unselect";
    private UserInfoBean mUserInfoBean;
    private String[] mTitles;
    private String[] mIconUnselectIds;
    private String[] mIconSelectIds;
    private ArrayList<TabEntity> mTabEntities = new ArrayList<>();


    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

//    @Override
//    public void onTabSelect(int position) {
//        viewPager.setCurrentItem(position);
//        this.position = position;
//    }
//
//    @Override
//    public void onTabReselect(int position) {
//
//    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//        slidingTabLayout.setmCurrentTab(position);
//        slidingTabLayout.setmCurrentPositionOffset(positionOffset);
//        slidingTabLayout.scrollToCurrentTab();
//        slidingTabLayout.invalidate();

        int offset = (int) (positionOffset * commonBottomTab.getmTabsContainer(position).getWidth());
        /**当前Tab的left+当前Tab的Width乘以positionOffset*/
        int newScrollX = commonBottomTab.getmTabsContainer(position).getLeft() + offset;

        if (position > 0 || offset > 0) {
            /**HorizontalScrollView移动到当前tab,并居中*/
            newScrollX -= scrollView.getWidth() / 2 - scrollView.getPaddingLeft();
            View currentTabView = commonBottomTab.getmTabsContainer(position);
            float left = currentTabView.getLeft();
            float right = currentTabView.getRight();

            //for mIndicatorWidthEqualTitle
            if (commonBottomTab.getIndicatorStyle() == 0 && true) {
                TextView tab_title = (TextView) currentTabView.findViewById(com.flyco.tablayout.R.id.tv_tab_title);
//                        mTextPaint.setTextSize(mTextsize);
                float textWidth = mTextPaint.measureText(tab_title.getText().toString());
                margin = (right - left - textWidth) / 2;
            }

            if (position < commonBottomTab.getTabCount() - 1) {
                View nextTabView = commonBottomTab.getmTabsContainer(position + 1);
                float nextTabLeft = nextTabView.getLeft();
                float nextTabRight = nextTabView.getRight();

                left = left + positionOffset * (nextTabLeft - left);
                right = right + positionOffset * (nextTabRight - right);

                //for mIndicatorWidthEqualTitle
                if (commonBottomTab.getIndicatorStyle() == 0 && true) {
                    TextView next_tab_title = (TextView) nextTabView.findViewById(com.flyco.tablayout.R.id.tv_tab_title);
//                            mTextPaint.setTextSize(mTextsize);
                    float nextTextWidth = mTextPaint.measureText(next_tab_title.getText().toString());
                    float nextMargin = (nextTabRight - nextTabLeft - nextTextWidth) / 2;
                    margin = margin + positionOffset * (nextMargin - margin);
                }
            }

            mIndicatorRect.left = (int) left;
            mIndicatorRect.right = (int) right;
            //for mIndicatorWidthEqualTitle
            if (commonBottomTab.getIndicatorStyle() == 0 && true) {
                mIndicatorRect.left = (int) (left + margin - 1);
                mIndicatorRect.right = (int) (right - margin - 1);
            }

            mTabRect.left = (int) left;
            mTabRect.right = (int) right;

            if (commonBottomTab.getIndicatorWidth() < 0) {   //indicatorWidth小于0时,原jpardogo's PagerSlidingTabStrip

            } else {//indicatorWidth大于0时,圆角矩形以及三角形
                float indicatorLeft = currentTabView.getLeft() + (currentTabView.getWidth() - commonBottomTab.getIndicatorWidth()) / 2;

                if (position < commonBottomTab.getTabCount() - 1) {
                    View nextTab = commonBottomTab.getmTabsContainer(position + 1);
                    indicatorLeft = indicatorLeft + positionOffset * (currentTabView.getWidth() / 2 + nextTab.getWidth() / 2);
                }

                mIndicatorRect.left = (int) indicatorLeft;
                mIndicatorRect.right = (int) (mIndicatorRect.left + commonBottomTab.getIndicatorWidth());
            }
            newScrollX += ((mTabRect.right - mTabRect.left) / 2);
        }

        if (newScrollX != mLastScrollX) {
            mLastScrollX = newScrollX;
            /** scrollTo（int x,int y）:x,y代表的不是坐标点,而是偏移量
             *  x:表示离起始位置的x水平方向的偏移量
             *  y:表示离起始位置的y垂直方向的偏移量
             */
            scrollView.scrollTo(newScrollX, 0);
        }
    }

    @Override
    public void onPageSelected(int position) {
//        slidingTabLayout.updateTabSelection(position);
        this.position = position;
        commonBottomTab.setCurrentTab(position);
        VideoViewManager.instance().pause();
    }

    @Override
    public void onPageScrollStateChanged(int i) {

    }

    boolean isFirstData = true;

    @Override
    public void onResume() {
        super.onResume();
//        if (isFirst) {
//            if (LocationUtil.getInstance().isStarted()) {
//                Logger.e("start");
//            } else {
//                Logger.e("end");
//                startLocation();
//            }
//        }else{
//            Logger.e("false");
//        }
//        if (!TextUtils.isEmpty(token)) {
//            handler.postDelayed(runnable, 5 * 60 * 1000);
//        }
    }

    @Override
    public void onStop() {
        super.onStop();
//        handler.removeCallbacks(runnable);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void OnMessageEvent(HomeLocationBean event) {
        flag = "select";
        EventBus.getDefault().post("finish_location");
        homeLocation.setText(event.getItem().getTitle());
        lat = event.getItem().getLatLonPoint().getLatitude();
        lon = event.getItem().getLatLonPoint().getLongitude();
        province = event.getItem().getProvinceName();
        if (event.getItem().getProvinceName().equals(event.getItem().getCityName())) {
            city = event.getItem().getAdName();
        } else {
            city = event.getItem().getCityName();
        }
//        Logger.e(event.getItem().getAdName()+"++"+event.getItem().getProvinceName()+"++"+event.getItem().getCityName());
        EventBus.getDefault().post("refresh_location_home:" + event.getItem().getLatLonPoint().getLatitude() + ":" + event.getItem().getLatLonPoint().getLongitude());
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void OnMessageEvent(HomeLocationData event) {
        flag = "unselect";
        EventBus.getDefault().post("finish_location");
        homeLocation.setText(event.getTitle());
        lat = event.getLat();
        lon = event.getLon();
        province = event.getProvice();
        if (event.getProvice().equals(event.getCity())) {
            city = event.getDis();
        } else {
            city = event.getCity();
        }
//        Logger.e(event.getItem().getAdName()+"++"+event.getItem().getProvinceName()+"++"+event.getItem().getCityName());
        EventBus.getDefault().post("refresh_location_home:" + event.getLat() + ":" + event.getLon());
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void OnMessageEvent(String event) {
        if (event.equals("home_scollTo_top")) {
            EventBus.getDefault().post("scollTo_top:" + mHomeTabBean.getList().get(position).getId());
        } else if (event.equals("home_refresh_data")) {
            if (flag.equals("select")) {
                EventBus.getDefault().post("refresh_data:" + mHomeTabBean.getList().get(position).getId());
            } else {
                startLocation();
            }
        } else if (event.equals("home_refresh_location")) {
            if (flag.equals("select")) {
                EventBus.getDefault().post("refresh_data:" + mHomeTabBean.getList().get(position).getId());
            } else {
                startLocation();
            }
        } else if ("dialog_activit".equals(event.split(" ")[0])) {
            activit_img.setVisibility(View.VISIBLE);
            Logger.e(event.split(" ")[1]);
            Glide.with(context)
                    .load(event.split(" ")[1])
                    .into(activit_img);

            activit_img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (Utils.isDoubleClick()) {
                        return;
                    }
                    HttpParams params = new HttpParams();
                    params.put("token", token);
                    finalOkGo.requestHead(RequestType.POSTHEAD, Url.VERIFY_TOKEN, params, Url.VERIFY_TOKEN, new Callback<SendCodeBean>() {
                        @Override
                        public void onSuccess(SendCodeBean sendCodeBean) {
                            if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                                //跳转h5
                                Logger.e(event.split(" ")[2]);
                                Bundle bundle = new Bundle();
                                bundle.putString("url", event.split(" ")[2] + "?token=" + token);
                                startActivity(FindBannerWebviewActivity.class, bundle);
                            }
                        }

                        @Override
                        public void onError(Response response) {
                            super.onError(response);
                        }
                    });
                }
            });
        } else if ("receiver_publish_pass".equals(event)) {
            home_tip_tv.setVisibility(View.GONE);
            mUserInfoBean.setIsInvitePublishTitle(0);
            SharedPreferencesHelp.putBean("userInfo", mUserInfoBean);
        }
    }

    //    @Override
    @OnClick({R.id.home_location, R.id.home_search, R.id.refresh_location, R.id.home_tip_tv})
    public void onViewClicked(View view) {
//        super.onViewClicked(view);
        if (Utils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.home_tip_tv:
                Bundle b = new Bundle();
                b.putString("flag", "out");
                b.putInt("count", 9);
                startActivity(CameraActivity.class, b);
                break;
            case R.id.refresh_location:
//                homeLocation.setText("定位中...");
//                LocationUtil.getInstance().startLocation();
                if (mAMapLocation != null) {
                    Bundle bundle = new Bundle();
                    bundle.putString("city", mAMapLocation.getCity());
                    bundle.putString("citycode", mAMapLocation.getCityCode());
                    bundle.putDouble("lat", mAMapLocation.getLatitude());
                    bundle.putDouble("lot", mAMapLocation.getLongitude());
                    bundle.putString("aoiName", homeLocation.getText().toString());
                    bundle.putString("flag", "home");
                    startActivity(LocationActivity.class, bundle);
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putString("flag", "home");
                    startActivity(LocationActivity.class, bundle);
                }
                break;
            case R.id.home_location:
                if (mAMapLocation != null) {
                    Bundle bundle = new Bundle();
                    bundle.putString("city", mAMapLocation.getCity());
                    bundle.putString("citycode", mAMapLocation.getCityCode());
                    bundle.putDouble("lat", mAMapLocation.getLatitude());
                    bundle.putDouble("lot", mAMapLocation.getLongitude());
                    bundle.putString("aoiName", homeLocation.getText().toString());
                    bundle.putString("flag", "home");
                    startActivity(LocationActivity.class, bundle);
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putString("flag", "home");
                    startActivity(LocationActivity.class, bundle);
                }
                break;
            case R.id.home_search:
                startActivity(SearchActivity.class);
                break;
        }
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        if (rxPermissions.isGranted(Manifest.permission.ACCESS_COARSE_LOCATION) && rxPermissions.isGranted(Manifest.permission.ACCESS_FINE_LOCATION)
                && rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE) && rxPermissions.isGranted(Manifest.permission.READ_EXTERNAL_STORAGE)
                /*&& rxPermissions.isGranted(Manifest.permission.READ_PHONE_STATE)*/) {
            refreshLayout.setEnableRefresh(false);
            LocationUtil.getInstance().locationOption();
            LocationUtil.getInstance().setLocationListener(this);
            LocationUtil.getInstance().startLocation();
        } else {
            rxPermissions.request(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE/*, Manifest.permission.READ_PHONE_STATE*/).subscribe(aBoolean -> {
                if (aBoolean) {
                    refreshLayout.setEnableRefresh(false);
                    LocationUtil.getInstance().locationOption();
                    LocationUtil.getInstance().setLocationListener(HomeFragment.this);
                    LocationUtil.getInstance().startLocation();
                } else {
                    refreshLayout.finishRefresh();
                    refreshLayout.setEnableRefresh(false);
                    showImageToas("拒绝定位权限 无法获取定位");
                }
            });
        }

        refreshLayout.finishRefresh();
    }

    private class MyPagerAdapter extends FragmentPagerAdapter {
        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitles[position];
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }
    }

    private Paint mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private float margin;
    private Rect mIndicatorRect = new Rect();
    private Rect mTabRect = new Rect();
    private int mLastScrollX;

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        unbinder = ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);

//        refreshLayout.setOnRefreshLoadMoreListener(this);
//        refreshLayout.setRefreshHeader(new MaterialHeader(context).setColorSchemeResources(R.color.common_color));
//        refreshLayout.setEnableLoadMore(false);

        viewPager.addOnPageChangeListener(this);
//        slidingTabLayout.setOnTabSelectListener(this);
        commonBottomTab.setOnTabSelectListener(new OnTabSelectListener() {

            @Override
            public void onTabSelect(int position) {
                viewPager.setCurrentItem(position);
                HomeFragment.this.position = position;
            }

            @Override
            public void onTabReselect(int position) {
//
            }

        });


//        slidingTabLayout.setviewPager(viewPager);


        token = (String) SharedPreferencesHelp.get("token", "");

        cacheLocationBean = (CacheLocationBean) SharedPreferencesHelp.getBean("cp_loaction");

        if (cacheLocationBean != null && !TextUtils.isEmpty(cacheLocationBean.getAdCode())) {
            Logger.e("cacheLocationBean!=null");
//            refreshLayout.finishRefresh();
            lat = cacheLocationBean.getLatitude();
            lon = cacheLocationBean.getLongitude();
            province = cacheLocationBean.getProvince();
            if (cacheLocationBean.getProvince().equals(cacheLocationBean.getCity())) {
                city = cacheLocationBean.getDistrict();
            } else {
                city = cacheLocationBean.getCity();
            }

            homeLocation.setText(cacheLocationBean.getAoiName().equals("") ? cacheLocationBean.getPoiName() : cacheLocationBean.getAoiName());

            finalOkGo.request(RequestType.POST, Url.HOME_TAB, null, Url.HOME_TAB, new Callback<HomeTabBean>() {
                @Override
                public void onSuccess(HomeTabBean homeTabBean) {
                    if (homeTabBean.getCode() == Contacts.SUCCESS) {
                        mTabEntities = new ArrayList<>();
                        mTitles = new String[homeTabBean.getList().size()];
                        mIconUnselectIds = new String[homeTabBean.getList().size()];
                        mIconSelectIds = new String[homeTabBean.getList().size()];

//                        list = new ArrayList<>();
                        mFragments = new ArrayList<>();//存放Fragment
                        mHomeTabBean = homeTabBean;
                        for (int i = 0; i < homeTabBean.getList().size(); i++) {
                            mFragments.add(RecommendFragment.newInstance(homeTabBean.getList().get(i).getId() + "", cacheLocationBean.getLatitude(), cacheLocationBean.getLongitude()));
//                            list.add(homeTabBean.getList().get(i).getName());
//                            if (!TextUtils.isEmpty(homeTabBean.getList().get(i).getName())) {
//                                mTitles[i] = homeTabBean.getList().get(i).getName();
//                            } else {
//                                mTitles[i] = "";
//                            }

                            if (!TextUtils.isEmpty(homeTabBean.getList().get(i).getImage())) {
                                mIconUnselectIds[i] = homeTabBean.getList().get(i).getImage();
                                mIconSelectIds[i] = homeTabBean.getList().get(i).getImage();
                            } else {
                                mTitles[i] = homeTabBean.getList().get(i).getName();
                                mIconUnselectIds[i] = "";
                                mIconSelectIds[i] = "";
                            }
                            mTabEntities.add(new TabEntity(mTitles[i], mIconSelectIds[i], mIconUnselectIds[i]));
                        }
                        myPagerAdapter = new MyPagerAdapter(getChildFragmentManager());
                        viewPager.setAdapter(myPagerAdapter);
                        commonBottomTab.setTabData(mTabEntities);
                        viewPager.setCurrentItem(position);
                        viewPager.setOffscreenPageLimit(7);
//                        slidingTabLayout.setmTitles(list);
//                        slidingTabLayout.notifyDataSetChanged();
                    } else {
                        showImageToas("获取首页标签失败");
                    }
                }

                @Override
                public void onError(Response<String> response) {
                    super.onError(response);
                }
            });


            if (!TextUtils.isEmpty(token)) {
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("adCode", cacheLocationBean.getAdCode());
                    jsonObject.put("province", cacheLocationBean.getProvince());
                    jsonObject.put("city", cacheLocationBean.getCity());
                    jsonObject.put("district", cacheLocationBean.getDistrict());
                    jsonObject.put("street", cacheLocationBean.getStreet());
                    jsonObject.put("poiName", cacheLocationBean.getPoiName());
                    jsonObject.put("aoiName", cacheLocationBean.getAoiName());
                    jsonObject.put("longitude", cacheLocationBean.getLongitude() + "");
                    jsonObject.put("latitude", cacheLocationBean.getLatitude() + "");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Logger.e(jsonObject.toString());
                finalOkGo.requestHead(RequestType.POSTJSONHEAD, Url.APP_LOCATION_SAVE, null, jsonObject.toString(), new Callback<SendCodeBean>() {
                    @Override
                    public void onSuccess(SendCodeBean sendCodeBean) {
                        if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                            JSONObject jsonObject = new JSONObject();
                            try {
                                jsonObject.put("address", cacheLocationBean.getProvince() + cacheLocationBean.getCity() + cacheLocationBean.getDistrict());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            finalOkGo.requestHead(RequestType.POSTJSONHEAD, Url.CHANGE_USERINFO, null, jsonObject.toString(), new Callback<SendCodeBean>() {
                                @Override
                                public void onSuccess(SendCodeBean sendCodeBean) {
                                    if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                                    } else {
                                        if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                                        } else {
                                            showImageToas(sendCodeBean.getMsg());
                                        }
                                    }
                                }

                                @Override
                                public void onError(Response<String> response) {
                                    super.onError(response);
                                }
                            });
                        } else {
                            if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                            } else {
                                showImageToas(sendCodeBean.getMsg());
                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                    }
                });

                handler.postDelayed(runnable, 5 * 60 * 1000);

            }

            startLocation();
        } else {
            Logger.e("定位中");
            homeLocation.setText("定位中...");

            startLocation();
        }

        return view;
    }

    private void startLocation() {
//        isFirst = true;
        if (rxPermissions.isGranted(Manifest.permission.ACCESS_COARSE_LOCATION) && rxPermissions.isGranted(Manifest.permission.ACCESS_FINE_LOCATION)
                && rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE) && rxPermissions.isGranted(Manifest.permission.READ_EXTERNAL_STORAGE)
                /*&& rxPermissions.isGranted(Manifest.permission.READ_PHONE_STATE)*/) {

//            refreshLayout.setEnableRefresh(false);
            LocationUtil.getInstance().locationOption();
            LocationUtil.getInstance().setLocationListener(this);
            LocationUtil.getInstance().startLocation();
        } else {
            rxPermissions.request(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE/*, Manifest.permission.READ_PHONE_STATE*/).subscribe(aBoolean -> {
                if (aBoolean) {
//                    refreshLayout.setEnableRefresh(false);
                    LocationUtil.getInstance().locationOption();
                    LocationUtil.getInstance().setLocationListener(HomeFragment.this);
                    LocationUtil.getInstance().startLocation();
                } else {
//                    refreshLayout.setEnableRefresh(false);
                    lat = 37.79457944304568;
                    lon = 112.54759994215532;
                    if (!isFirstData) {
                        EventBus.getDefault().post("refresh_location_home:" + lat + ":" + lon);
                    } else {
                        showImageToas("拒绝定位权限 无法获取定位");
                        homeLocation.setText("太原");
                        finalOkGo.request(RequestType.POST, Url.HOME_TAB, null, Url.HOME_TAB, new Callback<HomeTabBean>() {
                            @Override
                            public void onSuccess(HomeTabBean homeTabBean) {
                                if (homeTabBean.getCode() == Contacts.SUCCESS) {
                                    mTabEntities = new ArrayList<>();
                                    mTitles = new String[homeTabBean.getList().size()];
                                    mIconUnselectIds = new String[homeTabBean.getList().size()];
                                    mIconSelectIds = new String[homeTabBean.getList().size()];
//                                    list = new ArrayList<>();
                                    mFragments = new ArrayList<>();//存放Fragment
                                    mHomeTabBean = homeTabBean;
                                    for (int i = 0; i < homeTabBean.getList().size(); i++) {
                                        mFragments.add(RecommendFragment.newInstance(homeTabBean.getList().get(i).getId() + "", lat, lon));
//                                        list.add(homeTabBean.getList().get(i).getName());
//                                        if (!TextUtils.isEmpty(homeTabBean.getList().get(i).getName())) {
//                                            mTitles[i] = homeTabBean.getList().get(i).getName();
//                                        } else {
//                                            mTitles[i] = "";
//                                        }

                                        if (!TextUtils.isEmpty(homeTabBean.getList().get(i).getImage())) {
                                            mIconUnselectIds[i] = homeTabBean.getList().get(i).getImage();
                                            mIconSelectIds[i] = homeTabBean.getList().get(i).getImage();
                                        } else {
                                            mTitles[i] = homeTabBean.getList().get(i).getName();
                                            mIconUnselectIds[i] = "";
                                            mIconSelectIds[i] = "";
                                        }
                                        mTabEntities.add(new TabEntity(mTitles[i], mIconSelectIds[i], mIconUnselectIds[i]));
                                    }
                                    myPagerAdapter = new MyPagerAdapter(getChildFragmentManager());
                                    viewPager.setAdapter(myPagerAdapter);
                                    commonBottomTab.setTabData(mTabEntities);
                                    viewPager.setCurrentItem(position);
                                    viewPager.setOffscreenPageLimit(7);
//                                    slidingTabLayout.setmTitles(list);
//                                    slidingTabLayout.notifyDataSetChanged();

                                } else {
                                    showImageToas("获取首页标签失败");
                                }
                            }

                            @Override
                            public void onError(Response<String> response) {
                                super.onError(response);
                            }
                        });
                    }
                }
            });
        }
    }

    @Override
    protected void initData() {
        finalOkGo.request(RequestType.POST, Url.APP_VERSION_UPDATE, null, Url.APP_VERSION_UPDATE, new Callback<VersionBean>() {
            @Override
            public void onSuccess(VersionBean versionBean) {
                if (versionBean.getCode() == Contacts.SUCCESS) {
                    mUserInfoBean = (UserInfoBean) SharedPreferencesHelp.getBean("userInfo");
                    if (mUserInfoBean != null && mUserInfoBean.getIsInvitePublishTitle() == 1) {
                        home_tip_tv.setVisibility(View.VISIBLE);
                        home_tip_tv.setText(versionBean.getInvitePublishTitle());
                    } else {
                        home_tip_tv.setVisibility(View.GONE);
                    }
                }
            }
        });

    }

    //声明定位回调监听器
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        MobclickAgent.onEvent(ContextUtil.getContext(), "locationID");
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
//                refreshLayout.finishRefresh();

                if (cacheLocationBean != null && !TextUtils.isEmpty(cacheLocationBean.getAdCode())) {
                    if (cacheLocationBean.getAoiName().equals(aMapLocation.getAoiName()) || cacheLocationBean.getPoiName().equals(aMapLocation.getPoiName())) {
                        mAMapLocation = aMapLocation;
                        province = aMapLocation.getProvince();
                        if (aMapLocation.getProvince().equals(aMapLocation.getCity())) {
                            city = aMapLocation.getDistrict();
                        } else {
                            city = aMapLocation.getCity();
                        }

                        if (!TextUtils.isEmpty(aMapLocation.getAoiName())) {
                            homeLocation.setText(aMapLocation.getAoiName());
                        } else {
                            if (!TextUtils.isEmpty(aMapLocation.getPoiName())) {
                                homeLocation.setText(aMapLocation.getPoiName());
                            } else {
                                homeLocation.setText("太原市");
                            }
                        }
                        if (!isFirstData) {
                            EventBus.getDefault().post("refresh_location_home:" + aMapLocation.getLatitude() + ":" + aMapLocation.getLongitude());
                        }
                        isFirstData = false;
                    } else {
                        location(aMapLocation);
                    }
                } else {
                    location(aMapLocation);
                }

                LocationUtil.getInstance().stopLocation();//停止定位后，本地定位服务并不会被销毁
            } else {
//                refreshLayout.finishRefresh();
//                LocationManager locationManager
//                        = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//                // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
//                boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
//                // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
//                boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
//                if (gps || network) {
//                    refreshLayout.setEnableRefresh(false);
//                } else {
//                    refreshLayout.setEnableRefresh(true);
//                }
                //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                Logger.e("AmapError--" + "location Error, ErrCode:"
                        + aMapLocation.getErrorCode() + ", errInfo:"
                        + aMapLocation.getErrorInfo());
                lat = 37.79457944304568;
                lon = 112.54759994215532;
                if (!isFirstData) {
                    EventBus.getDefault().post("refresh_location_home:" + lat + ":" + lon);
                } else {
                    showImageToas("您似乎关闭了位置服务，请在设置中打开");
                    homeLocation.setText("太原");
                    finalOkGo.request(RequestType.POST, Url.HOME_TAB, null, Url.HOME_TAB, new Callback<HomeTabBean>() {
                        @Override
                        public void onSuccess(HomeTabBean homeTabBean) {
                            if (homeTabBean.getCode() == Contacts.SUCCESS) {
                                isFirstData = false;
                                mTabEntities = new ArrayList<>();
                                mTitles = new String[homeTabBean.getList().size()];
                                mIconUnselectIds = new String[homeTabBean.getList().size()];
                                mIconSelectIds = new String[homeTabBean.getList().size()];
//                                list = new ArrayList<>();
                                mFragments = new ArrayList<>();//存放Fragment
                                mHomeTabBean = homeTabBean;
                                for (int i = 0; i < homeTabBean.getList().size(); i++) {
                                    mFragments.add(RecommendFragment.newInstance(homeTabBean.getList().get(i).getId() + "", lat, lon));
//                                    list.add(homeTabBean.getList().get(i).getName());
//                                    if (!TextUtils.isEmpty(homeTabBean.getList().get(i).getName())) {
//                                        mTitles[i] = homeTabBean.getList().get(i).getName();
//                                    } else {
//                                        mTitles[i] = "";
//                                    }

                                    if (!TextUtils.isEmpty(homeTabBean.getList().get(i).getImage())) {
                                        mIconUnselectIds[i] = homeTabBean.getList().get(i).getImage();
                                        mIconSelectIds[i] = homeTabBean.getList().get(i).getImage();
                                    } else {
                                        mTitles[i] = homeTabBean.getList().get(i).getName();
                                        mIconUnselectIds[i] = "";
                                        mIconSelectIds[i] = "";
                                    }
                                    mTabEntities.add(new TabEntity(mTitles[i], mIconSelectIds[i], mIconUnselectIds[i]));
                                }
                                myPagerAdapter = new MyPagerAdapter(getChildFragmentManager());
                                viewPager.setAdapter(myPagerAdapter);
                                commonBottomTab.setTabData(mTabEntities);
                                viewPager.setCurrentItem(position);
                                viewPager.setOffscreenPageLimit(7);
//                                slidingTabLayout.setmTitles(list);
//                                slidingTabLayout.notifyDataSetChanged();

                            } else {
                                showImageToas("获取首页标签失败");
                            }
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                        }
                    });
                }

            }
        }
    }

    private void location(AMapLocation aMapLocation) {
        lat = aMapLocation.getLatitude();
        lon = aMapLocation.getLongitude();

        finalOkGo.request(RequestType.POST, Url.HOME_TAB, null, Url.HOME_TAB, new Callback<HomeTabBean>() {
            @Override
            public void onSuccess(HomeTabBean homeTabBean) {
                if (homeTabBean.getCode() == Contacts.SUCCESS) {
                    if (mTabEntities != null && mTabEntities.size() < homeTabBean.getList().size()) {
                        mTabEntities = new ArrayList<>();
                        mTitles = new String[homeTabBean.getList().size()];
                        mIconUnselectIds = new String[homeTabBean.getList().size()];
                        mIconSelectIds = new String[homeTabBean.getList().size()];
//                        list = new ArrayList<>();
                        mFragments = new ArrayList<>();//存放Fragment
                        mHomeTabBean = homeTabBean;
                        for (int i = 0; i < homeTabBean.getList().size(); i++) {
                            mFragments.add(RecommendFragment.newInstance(homeTabBean.getList().get(i).getId() + "", aMapLocation.getLatitude(), aMapLocation.getLongitude()));
//                            list.add(homeTabBean.getList().get(i).getName());
//                            if (!TextUtils.isEmpty(homeTabBean.getList().get(i).getName())) {
//                                mTitles[i] = homeTabBean.getList().get(i).getName();
//                            } else {
//                                mTitles[i] = "";
//                            }

                            if (!TextUtils.isEmpty(homeTabBean.getList().get(i).getImage())) {
                                mIconUnselectIds[i] = homeTabBean.getList().get(i).getImage();
                                mIconSelectIds[i] = homeTabBean.getList().get(i).getImage();
                            } else {
                                mTitles[i] = homeTabBean.getList().get(i).getName();
                                mIconUnselectIds[i] = "";
                                mIconSelectIds[i] = "";
                            }
                            mTabEntities.add(new TabEntity(mTitles[i], mIconSelectIds[i], mIconUnselectIds[i]));
                        }
                        myPagerAdapter = new MyPagerAdapter(getChildFragmentManager());
                        viewPager.setAdapter(myPagerAdapter);
                        commonBottomTab.setTabData(mTabEntities);
                        viewPager.setCurrentItem(position);
                        viewPager.setOffscreenPageLimit(7);
                        myPagerAdapter.notifyDataSetChanged();

//                        slidingTabLayout.setmTitles(list);
//                        slidingTabLayout.notifyDataSetChanged();
                    }

                    if (cacheLocationBean != null && !TextUtils.isEmpty(cacheLocationBean.getAdCode())) {
                        if (!cacheLocationBean.getAoiName().equals(aMapLocation.getAoiName()) || !cacheLocationBean.getPoiName().equals(aMapLocation.getPoiName())) {
                            EventBus.getDefault().post("refresh_location_home:" + aMapLocation.getLatitude() + ":" + aMapLocation.getLongitude());
                        } else {
                            if (!isFirstData) {
                                EventBus.getDefault().post("refresh_location_home:" + aMapLocation.getLatitude() + ":" + aMapLocation.getLongitude());
                            }
                            isFirstData = false;
                        }
                    } else {
                        if (!isFirstData) {
                            EventBus.getDefault().post("refresh_location_home:" + aMapLocation.getLatitude() + ":" + aMapLocation.getLongitude());
                        }
                        isFirstData = false;
                    }

                } else {
                    showImageToas("获取首页标签失败");
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
            }
        });

        Logger.e(aMapLocation.getLatitude() + "---" +
                aMapLocation.getLongitude() + "---" +
                aMapLocation.getAddress() + "---" +
                aMapLocation.getDistrict() + "---" +
                aMapLocation.getStreet() + "---" +
                aMapLocation.getStreetNum() + "---" +
                aMapLocation.getAoiName() + "---" +
                aMapLocation.getPoiName() + "---" +
                aMapLocation.getBuildingId() + "---" +
                aMapLocation.getFloor() + "---" +
                aMapLocation.getDescription());

        if (TextUtils.isEmpty(aMapLocation.getAdCode())) {
            //根据经纬度去进行查询地理信息
            LatLonPoint point = new LatLonPoint(aMapLocation.getLatitude(), aMapLocation.getLongitude());
            RegeocodeQuery query = new RegeocodeQuery(point, 200F, GeocodeSearch.AMAP);
            GeocodeSearch geocoderSearch = new GeocodeSearch(context);
            geocoderSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
                @Override
                public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
//                    Logger.e("逆定位数据" + regeocodeResult.getRegeocodeAddress().getAdCode()
//                            + "+++" + regeocodeResult.getRegeocodeAddress().getBuilding()
//                            + "+++" + regeocodeResult.getRegeocodeAddress().getCity()
//                            + "+++" + regeocodeResult.getRegeocodeAddress().getCityCode()
//                            + "+++" + regeocodeResult.getRegeocodeAddress().getCountry()
//                            + "+++" + regeocodeResult.getRegeocodeAddress().getDistrict()
//                            + "+++" + regeocodeResult.getRegeocodeAddress().getFormatAddress()
//                            + "+++" + regeocodeResult.getRegeocodeAddress().getNeighborhood()
//                            + "+++" + regeocodeResult.getRegeocodeAddress().getProvince()
//                            + "+++" + regeocodeResult.getRegeocodeAddress().getTownship()
//                            + "+++" + regeocodeResult.getRegeocodeAddress().getRoads().get(0).getName()
//                            + "+++" + regeocodeResult.getRegeocodeAddress().getAois().get(0).getAoiName()
//                            + "+++" + regeocodeResult.getRegeocodeAddress().getPois().get(0).getTitle());

                    //在这里解析得到的结果
                    province = regeocodeResult.getRegeocodeAddress().getProvince();
                    if (regeocodeResult.getRegeocodeAddress().getProvince().equals(regeocodeResult.getRegeocodeAddress().getCity())) {
                        city = regeocodeResult.getRegeocodeAddress().getDistrict();
                    } else {
                        city = regeocodeResult.getRegeocodeAddress().getCity();
                    }

                    if (regeocodeResult.getRegeocodeAddress().getAois().size() != 0) {
                        homeLocation.setText(regeocodeResult.getRegeocodeAddress().getAois().get(0).getAoiName());
                    } else {
                        if (regeocodeResult.getRegeocodeAddress().getPois().size() != 0) {
                            homeLocation.setText(regeocodeResult.getRegeocodeAddress().getPois().get(0).getTitle());
                        } else {
                            homeLocation.setText("太原市");
                        }
                    }

                    CacheLocationBean cacheLocationBean = new CacheLocationBean();
                    cacheLocationBean.setAdCode(regeocodeResult.getRegeocodeAddress().getAdCode());
                    cacheLocationBean.setProvince(regeocodeResult.getRegeocodeAddress().getProvince());
                    cacheLocationBean.setCity(regeocodeResult.getRegeocodeAddress().getCity());
                    cacheLocationBean.setDistrict(regeocodeResult.getRegeocodeAddress().getDistrict());
                    cacheLocationBean.setStreet(regeocodeResult.getRegeocodeAddress().getTownship());
                    if (regeocodeResult.getRegeocodeAddress().getPois().size() != 0) {
                        cacheLocationBean.setPoiName(regeocodeResult.getRegeocodeAddress().getPois().get(0).getTitle());
                    } else {
                        cacheLocationBean.setPoiName("");
                    }
                    if (regeocodeResult.getRegeocodeAddress().getAois().size() != 0) {
                        cacheLocationBean.setAoiName(regeocodeResult.getRegeocodeAddress().getAois().get(0).getAoiName());
                    } else {
                        cacheLocationBean.setAoiName("");
                    }
                    cacheLocationBean.setLongitude(aMapLocation.getLongitude());
                    cacheLocationBean.setLatitude(aMapLocation.getLatitude());
                    SharedPreferencesHelp.putBean("cp_loaction", cacheLocationBean);

                    if (!TextUtils.isEmpty(token)) {
                        JSONObject jsonObject = new JSONObject();
                        try {
                            jsonObject.put("adCode", regeocodeResult.getRegeocodeAddress().getAdCode());
                            jsonObject.put("province", regeocodeResult.getRegeocodeAddress().getProvince());
                            jsonObject.put("city", regeocodeResult.getRegeocodeAddress().getCity());
                            jsonObject.put("district", regeocodeResult.getRegeocodeAddress().getDistrict());
                            jsonObject.put("street", regeocodeResult.getRegeocodeAddress().getTownship());
                            if (regeocodeResult.getRegeocodeAddress().getPois().size() != 0) {
                                jsonObject.put("poiName", regeocodeResult.getRegeocodeAddress().getPois().get(0).getTitle());
                            } else {
                                jsonObject.put("poiName", "");
                            }
                            if (regeocodeResult.getRegeocodeAddress().getAois().size() != 0) {
                                jsonObject.put("aoiName", regeocodeResult.getRegeocodeAddress().getAois().get(0).getAoiName());
                            } else {
                                jsonObject.put("aoiName", "");
                            }
                            jsonObject.put("longitude", aMapLocation.getLongitude() + "");
                            jsonObject.put("latitude", aMapLocation.getLatitude() + "");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        Logger.e(jsonObject.toString());
                        finalOkGo.requestHead(RequestType.POSTJSONHEAD, Url.APP_LOCATION_SAVE, null, jsonObject.toString(), new Callback<SendCodeBean>() {
                            @Override
                            public void onSuccess(SendCodeBean sendCodeBean) {
                                if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                                    JSONObject jsonObject = new JSONObject();
                                    try {
                                        jsonObject.put("address", regeocodeResult.getRegeocodeAddress().getProvince() + regeocodeResult.getRegeocodeAddress().getCity() + regeocodeResult.getRegeocodeAddress().getDistrict());
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                    finalOkGo.requestHead(RequestType.POSTJSONHEAD, Url.CHANGE_USERINFO, null, jsonObject.toString(), new Callback<SendCodeBean>() {
                                        @Override
                                        public void onSuccess(SendCodeBean sendCodeBean) {
                                            if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                                            } else {
                                                showImageToas(sendCodeBean.getMsg());
                                            }
                                        }

                                        @Override
                                        public void onError(Response<String> response) {
                                            super.onError(response);
                                        }
                                    });
                                } else {
                                    showImageToas(sendCodeBean.getMsg());
                                }
                            }

                            @Override
                            public void onError(Response<String> response) {
                                super.onError(response);
                            }
                        });

                        handler.postDelayed(runnable, 5 * 60 * 1000);
//
                    }
                }

                @Override
                public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

                }

            });
            geocoderSearch.getFromLocationAsyn(query);
        } else {
            mAMapLocation = aMapLocation;
            province = aMapLocation.getProvince();
            if (aMapLocation.getProvince().equals(aMapLocation.getCity())) {
                city = aMapLocation.getDistrict();
            } else {
                city = aMapLocation.getCity();
            }

            //可在其中解析amapLocation获取相应内容。
//                aMapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
//                aMapLocation.getLatitude();//获取纬度
//                aMapLocation.getLongitude();//获取经度
//                aMapLocation.getAccuracy();//获取精度信息
//                aMapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
//                aMapLocation.getCountry();//国家信息
//                aMapLocation.getProvince();//省信息
//                aMapLocation.getCity();//城市信息
//                aMapLocation.getDistrict();//城区信息
//                aMapLocation.getStreet();//街道信息
//                aMapLocation.getStreetNum();//街道门牌号信息
//                aMapLocation.getCityCode();//城市编码
//                aMapLocation.getAdCode();//地区编码
//                aMapLocation.getAoiName();//获取当前定位点的AOI信息
//                aMapLocation.getBuildingId();//获取当前室内定位的建筑物Id
//                aMapLocation.getFloor();//获取当前室内定位的楼层
//                aMapLocation.getGpsAccuracyStatus();//获取GPS的当前状态
//                //获取定位时间
//                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                Date date = new Date(aMapLocation.getTime());
//                df.format(date);

            if (!TextUtils.isEmpty(aMapLocation.getAoiName())) {
                homeLocation.setText(aMapLocation.getAoiName());
            } else {
                if (!TextUtils.isEmpty(aMapLocation.getPoiName())) {
                    homeLocation.setText(aMapLocation.getPoiName());
                } else {
                    homeLocation.setText("太原市");
                }
            }

            Logger.e("定位数据获取到了");

            CacheLocationBean cacheLocationBean = new CacheLocationBean();
            cacheLocationBean.setAdCode(aMapLocation.getAdCode());
            cacheLocationBean.setProvince(aMapLocation.getProvince());
            cacheLocationBean.setCity(aMapLocation.getCity());
            cacheLocationBean.setDistrict(aMapLocation.getDistrict());
            cacheLocationBean.setStreet(aMapLocation.getStreet());
            cacheLocationBean.setPoiName(aMapLocation.getPoiName());
            cacheLocationBean.setAoiName(aMapLocation.getAoiName());
            cacheLocationBean.setLongitude(aMapLocation.getLongitude());
            cacheLocationBean.setLatitude(aMapLocation.getLatitude());
            SharedPreferencesHelp.putBean("cp_loaction", cacheLocationBean);

            if (!TextUtils.isEmpty(token)) {
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("adCode", aMapLocation.getAdCode());
                    jsonObject.put("province", aMapLocation.getProvince());
                    jsonObject.put("city", aMapLocation.getCity());
                    jsonObject.put("district", aMapLocation.getDistrict());
                    jsonObject.put("street", aMapLocation.getStreet());
                    jsonObject.put("poiName", aMapLocation.getPoiName());
                    jsonObject.put("aoiName", aMapLocation.getAoiName());
                    jsonObject.put("longitude", aMapLocation.getLongitude() + "");
                    jsonObject.put("latitude", aMapLocation.getLatitude() + "");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Logger.e(jsonObject.toString());
                finalOkGo.requestHead(RequestType.POSTJSONHEAD, Url.APP_LOCATION_SAVE, null, jsonObject.toString(), new Callback<SendCodeBean>() {
                    @Override
                    public void onSuccess(SendCodeBean sendCodeBean) {
                        if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                            JSONObject jsonObject = new JSONObject();
                            try {
                                jsonObject.put("address", aMapLocation.getProvince() + aMapLocation.getCity() + aMapLocation.getDistrict());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            finalOkGo.requestHead(RequestType.POSTJSONHEAD, Url.CHANGE_USERINFO, null, jsonObject.toString(), new Callback<SendCodeBean>() {
                                @Override
                                public void onSuccess(SendCodeBean sendCodeBean) {
                                    if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                                    } else {
                                        showImageToas(sendCodeBean.getMsg());
                                    }
                                }

                                @Override
                                public void onError(Response<String> response) {
                                    super.onError(response);
                                }
                            });
                        } else {
                            showImageToas(sendCodeBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                    }
                });

                handler.postDelayed(runnable, 5 * 60 * 1000);

            }
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(runnable);

    }
}
